<template>
  <div>
    <h3>枪支管理</h3>
    <div class="container">
      <vxe-toolbar>
        <template #buttons>
          <el-row :gutter="20" type="flex">
            <el-col :span="4" style="display: flex;">
              <el-button @click="exportEvent" size="small" type="primary" icon="el-icon-download">导出</el-button>
              <el-button @click="printEvent"  size="small" type="primary" icon="el-icon-printer">打印</el-button>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.areaId" size="small" collapse-tags filterable clearable placeholder="选择区域" @change="areaChange">
                <el-option :label="item.name" :value="item.areaId" v-for="(item,index) in areaData" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.orgIdStr" size="small" multiple collapse-tags filterable clearable placeholder="选择组织机构">
                <el-option :label="item.name" :value="item.orgId" v-for="(item,index) in orgData" :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small" @click="selectOrgAll">全选</el-button>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-input size="small" v-model="searchForm.licenseScope" placeholder="输入开设项目"></el-input>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit" style="margin: 0 10px;"> 搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="4">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @keyup="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row :cell-style="cellStyle"
        :loading="loading" :data="dataList" @sort-change="sortChange">
        <vxe-table-column field="org" title="机构" sortable></vxe-table-column>
        <vxe-table-column field="licenseNum" title="许可证号" sortable></vxe-table-column>
        <vxe-table-column field="licenseScope" title="开设项目" sortable></vxe-table-column>
        <vxe-table-column field="beginDate" title="生效日期" sortable></vxe-table-column>
        <vxe-table-column field="endDate" title="截止日期" sortable></vxe-table-column>
        <vxe-table-column field="become" title="到期时间/天" sortable></vxe-table-column>
        <vxe-table-column field="memo" title="备注" sortable></vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
  </div>
</template>

<script>
  import { statistics_org4provence,statistics_area,orgGunLicence } from '@/api/statistics.js'
  export default {
    data() {
      return {
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_org: {},
        areaData: [],
        searchForm: {
          areaId: '',
          orgIdStr: [],
          licenseScope: '',
        },
        orgData: [],
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.getOrg4gun()
      })
    },
    methods: {
      searchSubmit() {
        let data = {}
        if(this.searchForm.orgIdStr.length!=0) data.orgIdStr = this.searchForm.orgIdStr.join(',')
        if(this.searchForm.licenseScope) data.licenseScope = this.searchForm.licenseScope
        orgGunLicence(data).then(res=>{
          if(res.code === 200 && res.data.length!=0){
            this.init_data(res.data)
          }else{
            this.defaultDataList = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      clearTableFilter() {
        this.searchForm = {
          areaId: '',
          orgIdStr: [],
          licenseScope: '',
        }
        this.doubleDate = ''
        this.getOrg4gun()
      },
      selectOrgAll() {
        this.searchForm.orgIdStr = []
        this.orgData.forEach(item=>{
          this.searchForm.orgIdStr.push(item.orgId)
        })
      },
      areaChange(val) {
        this.orgData = []
        this.searchForm.orgIdStr = ''
        statistics_org4provence({areaId:val}).then(res=>{
          this.orgData = res.data
        })
      },
      getOrg4gun() {
        orgGunLicence().then(res=>{
          if(res.code === 200 && res.data.length!=0) {
            this.init_data(res.data)
          }else{
            this.defaultDataList = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      cellStyle({ row, rowIndex, column }) {
        if(column.property == 'become'){
          if(row.style=='red'){
            return {
              backgroundColor: '#DC143C',
              color: '#ffffff'
            }
          }else if(row.style=='orange'){
            return {
              backgroundColor: 'orange',
              color: '#ffffff'
            }
          }
        }
      },
      init_data(data) {
        data.forEach(item=>{
          item.org = this.dict_org[item.orgId]
          if(!item.licenseNum) item.licenseNum = '请及时到相关部门办理合法资质'
          if(item.beginDate){
            item.beginDate = this.$moment(item.beginDate).format('YYYY-MM-DD')
          }else{
            item.beginDate = '请准确记录 生效日期'
          }
          if(item.endDate){
            item.endDate = this.$moment(item.endDate).format('YYYY-MM-DD')
            let now = this.$moment().format("YYYY-MM-DD")
            let flag = this.$moment(item.endDate).format("YYYY-MM-DD")
            let days = this.getDays(now, flag)
            if (days <= 0) {
                item.style = 'red'
                item.become = days + "(天)-该枪支持枪证已过期，请及时到相关机构办理相应手续"
            }else if (days > 0 && days <= 100) {
              item.style = 'orange'
                item.become = days + "(天)-该枪支持枪证临近有效期，请及时到相关机构办理相应手续"
            }else{
              item.become = days
            }
          }else{
            item.endDate = '请准确记录 截止日期'
          }
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      getDays(date1, date2) {
        //将日期字符串分隔为数组,数组元素分别为年.月.日
        var date1Str = date1.split("-");
        //根据年月日的值创建Date对象
        var date1Obj = new Date(date1Str[0], (date1Str[1] - 1), date1Str[2]);
        var date2Str = date2.split("-");
        var date2Obj = new Date(date2Str[0], (date2Str[1] - 1), date2Str[2]);
        var t1 = date1Obj.getTime();
        var t2 = date2Obj.getTime();
        //每一天的毫秒数
        var dateTime = 1000 * 60 * 60 * 24;
        //计算出两个日期的天数差
        var minusDays = Math.floor(((t2 - t1) / dateTime));
        //取绝对值
        return minusDays;
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          statistics_org4provence().then(res=>{
            this.orgData = res.data
            res.data.forEach(item=>{
              this.dict_org[item.orgId] = item.name
            })
          })
          statistics_area().then(res=>{
            this.areaData = res.data
            resolve()
          })
        })
      },
      exportEvent() {
        this.loading = true
        setTimeout(() => {
          this.$refs.XTable.exportData({
            filename: '枪支管理',
            isHeader: true,
            isFooter: true,
            data: this.defaultDataList
          })
          this.loading = false
        }, 100)
      },
      printEvent() {
        let topHtml = '<h2>枪支管理</h2>'
        let num = this.page.pageSize
        this.page.pageSize = this.defaultDataList.length
        this.findList()
        setTimeout(()=>{
          this.$refs.XTable.print({
              sheetName: '枪支管理',
              beforePrintMethod: ({content}) => {
                  return topHtml + content
              }
          })
          this.page.pageSize = num
          this.findList()
        },1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = new RegExp(filterName, 'gi')
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
        } else {
          this.dataList = this.defaultDataList
          this.findList()
        }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
        this.page.pageSize = this.defaultDataList.length
        this.findList()
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.defaultDataList.length
          this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
.container{
  padding: 10px;
  background-color: #FFFFFF;
}
</style>
